<?php

namespace app\common\models;

class UserToken extends BaseModel
{
    protected $name = 'token';

    public function getToken($user_id, $is_update = false, $type = 'user')
    {
        $create_time = NEW_TIME;
        $expire_time = $create_time + (3600 * 24 * 10);
        $token = $this->getField(['user_id'=>$user_id,'type'=>$type], 'token');
        if (!$is_update && !empty($token)){
            $this->setField(['user_id'=>$user_id,'type'=>$type], ['expiretime'=>$expire_time]);
        }else{
            $save_data = [
                'type'=>$type,
                'user_id'=>$user_id,
                'createtime'=>$create_time,
                'expiretime'=>$expire_time,
            ];
            $token = md5(sha1(http_build_query($save_data)));
            $save_data['token'] = $token;
            if (!empty($token)){
                $this->remove(['user_id'=>$user_id,'type'=>$type]);
            }
            $this->insert($save_data);
        }
        return $token;
    }

    public function tokenAuth($token)
    {
        $token_data = $this->getFind(['token'=>$token]);
        if (!empty($token_data)){
            if ($token_data['expiretime'] > NEW_TIME){
                $this->getToken($token_data['user_id'], false, $token_data['type']);
                return $token_data;
            }
        }
        return false;
    }
}